$(document).ready(function(){



	
	// //新增用户弹出窗口中用户类型默认选第一个
	
 	// 帐户名验证
	    jQuery.validator.addMethod("isUsername", function(value, element) {
	        // var username = /^[0-9_a-zA-Z]\w{2,30}$/g;
	        var username = /^[\u0391-\uFFE5\w]+$/;
	        return this.optional(element) || (username.test(value));
	    }, "不能输入特殊字符，请正确输入");
	    
	    //昵称验证
	    jQuery.validator.addMethod("isPassword", function(value, element) {

	    	 var password = /^[\u0391-\uFFE5\w]+$/; //校验字符中是否包含非法字符

	    	 // var chn =  /[^u4e00-u9fa5]/; //校验是否为中文
	        // return this.optional(element) || ( (password.test(value)) && (!chn.test(value))  );
	        return this.optional(element) || ( (password.test(value))   );
	    }, "不能输入特殊字符，请正确输入");

 		jQuery.validator.addMethod("isMobile", function(value, element) {
	        var length = value.length;
	        // var mobile = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
	        // var mobile = /^([0-9][-])+$/g ;
	        var mobile = /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)+$/g;
	        return this.optional(element) || (mobile.test(value));
	    }, "请正确填写您的手机号码");
	//为addUser注册validate函数
	$("#addUserForm").validate({
			event: "keyup" ,
			rules:{
				username:{
					isUsername:true,
					required:true,
					// minlength:3,
					maxlength:30
				},
				password:{
					isPassword:true,
					required:true,
					minlength:3,
					maxlength:60
				},
				crmPassword:{
					required:true,
					equalTo:"#input-adduser-password"
				},
				telephone:{
					isMobile:true
				},
				address:{
					email:true
				}
			},
			messages:{
				username:{
					required:"请输入用户名",
					// minlength: "用户名长度至少为 3字符",
					maxlength: "用户名长度最大为 30 字符"

				},
				password:{

					required: "请输入密码",
					minlength: "密码至少输入 3字符",
					maxlength: "密码长度最大为 30 字符"

				},
				crmPassword:{
					required: "请再次输入密码",
					equalTo: "密码输入不一致",
				},
				telephone:{
					isMobile:"请正确输入电话号码"
				},
				address:{
					email: "请正确输入邮箱地址"
				}
			},
			success: function(label) {
				//label指向上面那个错误提示信息标签em
				label.text("")				//清空错误提示消息
					.addClass("success");	//加上自定义的success类
			}
	});

	//为editUser注册validate函数
	$("#editUserForm").validate({
			event: "keyup" ,
			rules:{
				username:{
					isUsername:true,
					required:true,
					maxlength:30,
					isUsername:true
				},
				password:{
					isPassword:true,
					maxlength:30,
					minlength:3,
					isPassword:true
				},
				edit_crmPassword:{
					equalTo: "#edituser-password"
				},
				telephone:{
					isMobile:true
				}
				,
				address:{
					email:true
				}
				
			},
			messages:{
				username:{
					required:"请输入用户名",
					maxlength: "用户名长度最大为 30 字符"
				},
				password:{
					required:"请输入密码",
					minlength: "密码至少输入 3字符",
					maxlength: "密码长度最大为 30 字符"
				},
				edit_crmPassword:{
					required:"请再次输入密码",
					equalTo: "密码输入不一致"
				},
				telephone:{
					isMobile:"请正确输入电话号码"
				}
				,
				
				address:{
					email:"请正确输入邮箱地址"
				}
				// telephone:{

				// }

			},
			success: function(label) {
				//label指向上面那个错误提示信息标签em
				label.text("")				//清空错误提示消息
					.addClass("success");	//加上自定义的success类
			}
	});


	$("#setPasswordForm").validate({
			event: "keyup" ,
			rules:{
				password:{
					required:true,
					isPassword:true,
					maxlength:30,
					minlength:3,
					isPassword:true
				},
				edit_crmPassword:{
					equalTo: "#editpsw-password"
				}
				
				
			},
			messages:{
				password:{
					required:"请输入密码",
					minlength: "密码至少输入 3字符",
					maxlength: "密码长度最大为 30 字符"
				},
				edit_crmPassword:{
					required:"请再次输入密码",
					equalTo: "密码输入不一致"
				}
				
				

			},
			success: function(label) {
				//label指向上面那个错误提示信息标签em
				label.text("")				//清空错误提示消息
					.addClass("success");	//加上自定义的success类
			}
	});
});

/* 获取多选框项id */
function getIds() {
	var checkIds = [];
	// alert($("#userList input[type='checkbox']").length)
	$("#userListBody input[type='checkbox']").each(function(index) {

		if ($(this).is(':checked')) {
			var id = $(this).val();
			checkIds.push(id);
		}
	});

	return checkIds;
}


function showAddUserModal(){
	$("#input-adduser-username").html("");
	$("#input-adduser-password").html("");
	$("#input-adduser-address").html("");

	var roleList = $("#addUserRoleBody input[type='checkbox']");
	// 填充前清理多选框中内容
	// roleList.each(function(index) {
	// 	roleList[index].checked = false;
	// 	roleList[index].name = "roles" + "[" + index + "].id" ;
	// });
	$('#addUserModal').modal("show");
}

function addUser() {
	
	var username = $("#input-adduser-username");
	var password = $("#input-adduser-password");
//	var address = $("#input-adduser-address");
	var addUserForm = $("#addUserForm");
	

	if(addUserForm.valid()==false){
		// bootbox.alert("请正确输入相关信息");
		return false;
	}

	var roleIDs = getRoleIDs();

	//添加邮箱默认注册值  modify by lizhifeng邮箱默认为空
	//address.attr("value","");
	
	var data = $('#addUserForm').serialize();
	
	$.ajax({
		url : "addUserAndRoles",
		type : 'post',
		data : data,
		success : function(result) {
				// console.log(result);

			
			if(result == "success"){
				bootbox.alert("新增成功",function(){
					window.location.reload()
					$('#addUserModal').modal("hide");
				});
				
			} else if(result == "registered"){
				bootbox.alert("该用户已存在，请重新输入");
			} else if(result == "null"){
				bootbox.alert("请正确输入用户名和密码");
			} else{
				bootbox.alert("新增失败");
			}
			
		},
		error : function() {
			bootbox.alert(result);
		}
	});

}

function deleteUsers() {
	var ids = getIds();

			if (ids.length == 0) {
				bootbox.alert("请至少选择一项");
				return;
			}
	bootbox.confirm("确定要删除用户吗？",function(result){
		if(result){
			
			
			console.log(ids);
			var data = [ {
				name : 'ids',
				value : ids
			} ];
			$.ajax({
				url : "delete",
				type : 'post',
				data : data,
				success : function(result) {
					
					var reload = function(){
						var url = window.location.href;
//						if( url.split("?").length>1){
//							//不在第一页， 跳转回第一页。。。⊙﹏⊙b汗
//							//url = url.substr(0,url.length-1)+ "1";;
//							window.location.href = url;	
//						}
						if(url.indexOf("page=") > 0){
							url = url.replace("page=","old_pa=");
							url += "&page=1";
							window.location.href = url;
						}else{
							window.location.reload();
						}
					};

					bootbox.alert("删除成功",reload);
					
				},
				error : function() {
					bootbox.alert('删除失败');
				}
			});
		}else{
			return;
		}
		
	});
	
}

function lockUsers() {
	var ids = getIds();
	var data = [ {
		name : 'ids',
		value : ids
	} ];
	$.ajax({
		url : "lockUsers",
		type : 'post',
		data : data,
		success : function(result) {
			
			bootbox.alert(result,function(){
				window.location.reload();
			});
		},
		error : function() {
			bootbox.alert("服务器繁忙，请稍后再试！");
		}
	});
}

function setUserStatus(id, status) {

	//目前状态只有 n 和 d，直接至反。。
	if(status=="d"){
		status = "n";
	}else{
		status = "d";
	}

	var data = [ {
		name : 'id',
		value : id
	}, {
		name : 'status',
		value : status
	} ];
	$.ajax({
		url : "setUserStatus",
		type : 'post',
		data : data,
		success : function(result) {
			if(result.result=='success'){
				bootbox.alert("修改状态成功",function(){
					window.location.reload();		
				});	
			}
			
		},
		error : function() {
			bootbox.alert("服务器繁忙，请稍后再试！");
		}
	});
}

function resetPassword(userID) {
	var data = [ {name : 'id',value : userID} ];
	$.ajax({
		url : "resetPassword",
		type : 'post',
		data : data,
		success : function(result) {
			// alert(result);
			if(result=="success"){
				bootbox.alert("重置密码成功,默认密码为000000");
			}else{
				bootbox.alert("重置失败");
			}
		},
		error : function() {
			bootbox.alert("服务器繁忙，请稍后再试！");
		}
	});
}

function showPasswordModal(userID,username){
	var ed_userId = $('#editpsw-userId');
	var ed_username = $('#editpsw-username');
	var ed_password = $('#editpsw-password');
	var ed_password_confirm = $('#editpsw-password-confirm');
	var lb_username = $('#editpsw-lb_username');
	var btn_submitPassword = $("#btn-submitPassword");

	ed_userId.val(userID);
	ed_username.val(username);
	lb_username.html(username);
	
	ed_password.val("");
	ed_password_confirm.val("");

	btn_submitPassword.unbind('click');
	btn_submitPassword.on('click',function(){
		// alert(ed_password.val());
		// alert(userID+" ");
		setPassword(userID,ed_password.val());
	});
	$("#setPasswordModal").modal("show");
}

function setPassword(userID,password) {
	var form = $("#setPasswordForm");

	if( !form.valid() ){
		return;
	}

	var data = [ {name : 'id'		,	value : userID} ,
				 {name : 'password'	, 	value : password}];
	$.ajax({
		url : "setPassword",
		type : 'post',
		data : data,
		success : function(result) {
			
			if(result=="success"){
				bootbox.alert("修改密码成功",function(){
					$("#setPasswordModal").modal("hide");
				});

			}else{
				bootbox.alert("修改密码失败");
			}
		},
		error : function() {
			bootbox.alert("服务器繁忙，请稍后再试！");
		}
	});
}


function getRoleIDs() {
	var cIds = [];

	$("#addRole input[type='checkbox']").each(function(index) {
		if ($(this).is(':checked')) {
			var id = $(this).val();
			cIds.push(id);
		}
	});
	return cIds;
}

function addRoles(userID) {

	var roleIds = getRoleIDs();
	if (roleIds.length != 0) {
		var data = [ {
			name : 'userID',
			value : userID
		}, {
			name : 'roleIds',
			value : roleIds
		} ];

		$.ajax({
			url : "addRoles",
			type : 'post',
			data : data,
			success : function(result) {
				bootbox.alert(result,function(){
					window.location.reload();	
				});
				
			},
			error : function() {
				bootbox.alert("服务器繁忙，请稍后再试！");
			}
		});
	} else {
		window.location.reload();
	}

}

function editUser(userID) {
	var ed_userId = $('#edituser-userId');
	var ed_username = $('#edituser-username');
	var ed_name = $('#edituser-name');
	var ed_password = $('#edituser-password');
	var ed_address = $('#edituser-address');
	var ed_telephone = $('#edituser-telephone');
	var lb_username = $('#edituser-lb_username');
	var ed_status = $('#edituser-status');
	var roleList = $("#userRoleBody input[type='checkbox']");
	var sex = $("#edituser-sex input[type='radio']");

	var btn_submitUserInfo = $("#btn-submitUserInfo");

	btn_submitUserInfo.on('click',function(){
		submitEditUser(userID);
	})

	// 填充前清理多选框中内容
	roleList.each(function(index) {
		roleList[index].checked = false;
		// roleList[index].name = "roles" + "[" + index + "]" + ".id";
	});

	// ajax请求
	var data = [ {
		name : 'userId',
		value : userID
	} ];
	$.ajax({
		url : "getUserAndRoles",
		type : 'post',
		data : data,
		dataType : "json",
		success : function(user) {

			// 填装数据
			ed_name.attr('value', user.name);
			ed_username.attr('value', user.username);
			lb_username.html(user.username);
			ed_status.attr('value', user.status);
			ed_address.attr('value', user.address);
			ed_userId.attr('value', user.id);
			ed_telephone.attr('value',user.telephone);
			sex.each(function(index){

				if($(this).val() == user.sex){
					sex[index].checked=true;
				}
			});

			// 填充多选框
			for (i in user.roles) {
				roleList.each(function(index) {
					if (user.roles[i].id == $(this).val()) {
						roleList[index].checked = true;
					}
				});
			}
			// 打开窗口
			$('#editUserModal').modal("show");
		},
		error : function() {
			bootbox.alert("服务器繁忙，请稍后再试！");
		}
	});

}

function submitEditUser(userID){
	
	var form = $("#editUserForm");
	console.log(form);
	if(!form.valid()){
		// bootbox.alert("输入不合法，请重新输入");
        return;
	}
    $.ajax({
            cache: true,
            type: "POST",
            url:form.attr("action"),
            data: form.serialize(),// 你的formid
            async: false,
            error: function(request) {
                // alert("Connection error");
                bootbox.alert("提交失败");
            },
            success: function(data) {
                bootbox.alert("更新用户信息成功",function(){
                    window.location.reload();
                    $("#editUserModal").modal('hide');
                    $("#btn-submitUserInfo").unbind('click');
                });


            }
    });


}


function selectAll(id,parent){
	var selectAllCheckbox = $("#"+id);
	var checkList = $("#"+parent+" input[type='checkbox']");
	if(selectAllCheckbox.is(':checked')){
		checkList.each(function(index) {
			this.checked = true;
		});
	}else{
		checkList.each(function(index) {
			this.checked = false;
		});
	}
}

//EXCEL文件上传 
function uploadUser(){
	var path = $('#file').val();
	if(!path || path == ""){
		bootbox.alert("请选择Excel文件！");
		return false;
	}
	var houzhui=path.substr(path.indexOf("."));
	if(houzhui!=".xlsx" && houzhui!=".xls"){
		bootbox.alert("文件格式不正确！");
		return false;
	}
	
	$.ajaxFileUpload({
		url:ctx+'/rbac/user/importUser',
		secureuri:false,  
		fileElementId:'file', 
		dataType: 'json', 
		success: function (data, status){
			if("true" == data.result){
				bootbox.alert("导入成功！",function(){
					window.location.reload();	
				});
			}else{
				bootbox.alert(data.msg);
			}
		},
		 error: function (data, status, e){
			 bootbox.alert("导入失败！");
		 }
	});
}